package vendas.web.jsf;

import java.text.NumberFormat;
import java.util.Locale;
import java.util.regex.Pattern;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public class DoubleConverter implements Converter {

    private static NumberFormat numberFormat = null;

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String strValor) {

        if (strValor == null || strValor.toString().trim().equals("")) {
            return 0.0d;
        } else {
            strValor = strValor.replaceAll(Pattern.quote("."), "");
            try {
                return getNumberFormat().parse(strValor.replace(",", ".")).doubleValue();
            } catch (Exception e) {
                return 0.0d;
            }
        }
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object objValor) {

        if (objValor == null || objValor.toString().trim().equals("")) {
            return "0,00";
        } else {
            return getNumberFormat().format(Double.valueOf(objValor.toString()));
        }
    }

    private static NumberFormat getNumberFormat() {

        if (DoubleConverter.numberFormat == null) {
            DoubleConverter.numberFormat = NumberFormat.getInstance(new Locale("pt", "BR"));
            DoubleConverter.numberFormat.setMaximumFractionDigits(2);
        }
        return DoubleConverter.numberFormat;
    }

}
